/**
 *                            License
 * THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS  
 * CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). 
 * THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW.  
 * ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR  
 * COPYRIGHT LAW IS PROHIBITED.
 * 
 * BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND  
 * AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE  
 * MAY BE CONSIDERED TO BE A CONTRACT,
 * THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED 
 * HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
 * 
 */
package lineage.core.handler;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import lineage.core.L1GameClient;
import lineage.core.Opcodes;
import lineage.packet.L1AbstractPacketServer;
import lineage.util.StreamUtil;
import lineage.util.UByte8;
import lineage.util.UChar8;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 写处理器.
 * 完成读处理器交给的任务,即向客户端回应消息.
 * 
 * @version 2014年3月9日下午2:49:45
 * @author jrwz
 */
public final class L1WriteHandler extends L1AbstractHandler {
    private static final Logger LOG = LoggerFactory.getLogger(L1WriteHandler.class);

    /**
     * 写处理器.
     * 
     * @param client
     *            - 客户端
     * @param out
     *            - 输出流
     */
    public L1WriteHandler(final L1GameClient client, final OutputStream out) {
        this.client = client;
        this.out = new BufferedOutputStream(out);
        keys = client.getKeys();
        psh = new L1PacketSendHandler(client, this);
    }

    @Override
    public void executeQueue(final byte[] data) {
        psh.executeQueue(data); // 移交至封包发送管理器
    }

    /**
     * 进行处理(稍后由'封包发送管理器'发送至客户端).
     * 
     * @param packet
     *            - 要发送的服务端封包
     */
    public void executeQueue(final L1AbstractPacketServer packet) {
        byte[] data = null;
        try {
            data = packet.getContent();
        } catch (IOException e) {
            LOG.error(e.getLocalizedMessage(), e);
        } catch (Exception e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
        psh.executeQueue(data); // 移交至封包发送管理器
    }

    /**
     * 输出第一组封包.
     */
    public void outFirstPacket() {
        try {
            synchronized (this) {
                if (out != null) {
                    out.write(Opcodes.firstPacket);
                    out.flush(); // 刷新此输出流并强制写出所有缓冲的输出字节
                }
                keys.initKeys(Opcodes.seed);
            }
        } catch (final IOException e) {
            LOG.error(e.getLocalizedMessage(), e);
        } catch (final Exception e) {
            close();
            LOG.error(e.getLocalizedMessage(), e);
        }
    }

    // 加密
    @Override
    public byte[] toEncrypt(final byte[] data) throws Exception {
        char ed[] = null;
        if (data.length > 0 && client.getWrite() != null) {
            ed = new char[data.length];
            ed = UChar8.fromArray(data);
            ed = keys.encrypt(ed);
            if (ed != null) {
                return UByte8.fromArray(ed);
            }
        }
        throw new RuntimeException();
    }

    @Override
    public void close() {
        try {
            StreamUtil.close(out);
        } catch (final Exception e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
}
